<template>
  <div>
    <div id="themeArea"><label>主题切换</label></div>
    <div>
      <select name="nivcai" v-model="selectedTheme">
        <option value="macarons">macarons</option>
        <option value="dark">dark</option>
      </select>
    </div>
    <!-- 为ECharts准备一个具备大小（宽高）的Dom -->
    <div id="main1" style="width: 800px; height: 400px"></div>
    <div id="main2" style="width: 800px; height: 500px"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  data () {
    return {
      selectedTheme: 'macarons',
      myChart1: null,
      myChart2: null,
      option1: {
        title: {  //标题组件
          text: '主标题文本，支持\n换行',
          subtext: '副标题文本'
        },

        toolbox: {//工具栏组件
          show: true,
          feature: {
            dataView: { //数据视图工具
              readOnly: false//是否只读//true只读，不能编辑//false可编辑
            },

            dataZoom: {},//数据区域缩放}

            magicType: { type: ['line', 'bar', 'stack'] },//动态类型切换折线、柱状、堆叠图

            restore: {},//配置项还原

            saveAsImage: {//保存为图片
              pixelRatio: 1//保存图片的分辨率
            },

            // brush: {}//选框组件
          }
        },
        tooltip: { trigger: 'axis' },
        legend: {
          data: ['2019数据', '2020数据', '2021数据'],//必须与series中的name一致
          itemGap: 20,//图例之间的间距
        },
        dataZoom: [{
          type: 'inside',//内置型数据区域缩放组件
          show: true,
          start: 20,//窗口范围的起始百分比
          end: 70,
        }],
        xAxis: {
          type: 'category',
          data: ['汉口学院', '武汉商学院', '湖北大学', '湖北理工学院', '江汉大学', '长江大学', '湖北医药学院', '湖北工程学院']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '2019数据',
            data: [50, 91, 42, 63, 33, 25, 65, 94],
            type: 'bar'
          },
          {
            name: '2020数据',
            data: [47, 53, 66, 42, 39, 27, 62, 52],
            type: 'bar'
          },
          {
            name: '2021数据',
            data: [55, 95, 46, 33, 23, 53, 59, 64],
            type: 'bar'
          },
        ]
      },


      option2: {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'//提示框浮层内容格式器
          //{a}（系列名称），{b}（数据项名称），{c}（数值）, {d}（百分比）
        },
        legend: {
          data: [
            '汉口学院',
            '武汉商学院',
            '湖北大学',
            '湖北理工学院',
            '江汉大学',
            '长江大学',
            '湖北医药学院',
            '湖北工程学院',
          ]
        },
        series: [
          {
            name: '数据',
            type: 'pie',//饼图
            selectedMode: 'single',//单选，多选为multiple，
            radius: [0, '35%'],//饼图半径
            label: {
              position: 'inner',//饼图扇区内部//标签位置
              fontSize: 14
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 668, name: '云计算技术' },
              { value: 635, name: '大数据技术' },
              { value: 369, name: '计算机应用技术', selected: true }
            ]
          },
          {
            name: '数据',
            type: 'pie',
            radius: ['45%', '65%'],
            labelLine: {
              length: 30
            },
            label: {
              formatter: '{b|{b}：}{c}  {per|{d}%}  ',
              backgroundColor: '#F6F8FC',
              borderColor: '#8C8D8E',
              borderWidth: 1,
              borderRadius: 4,
              rich: {
                a: {
                  color: '#6E7079',
                  lineHeight: 22,
                  align: 'center'
                },
                hr: {
                  borderColor: '#8C8D8E',
                  width: '100%',
                  borderWidth: 1,
                  height: 0
                },
                b: {
                  color: '#4C5058',
                  fontSize: 14,
                  fontWeight: 'bold',
                  lineHeight: 33
                },
                per: {
                  color: '#fff',
                  backgroundColor: '#4C5058',
                  padding: [3, 4],
                  borderRadius: 4
                }
              }
            },
            data: [
              { value: 308, name: '汉口学院' },
              { value: 235, name: '湖北工程学院' },
              { value: 210, name: '武汉商学院' },
              { value: 251, name: '湖北医药学院' },
              { value: 221, name: '湖北理工学院' },
              { value: 34, name: '湖北大学' },
              { value: 147, name: '移速' },
              { value: 35, name: '江汉大学' },
              { value: 52, name: '长江大学' }
            ]
          }
        ]
      }
    };
  },
  mounted () {
    this.initCharts().then(() => {
      this.loadTheme(this.selectedTheme);
    }).catch(error => {
      console.error('Failed to initialize charts:', error);
    });
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy () {
    window.removeEventListener("resize", this.handleResize);
  },
  watch: {//响应式数据变化
    selectedTheme (newVal) {//newval:新传入的值
      this.loadTheme(newVal);
    }
  },
  methods: {
    /**加载主题文件 */
    loadTheme (theme) {
      const script = document.createElement('script');
      script.src = `/resources/theme/${theme}.js`;
      script.onload = () => {
        console.log(`${theme} theme loaded successfully`);
        this.updateChartsTheme(theme);
      };
      script.onerror = (error) => {
        console.error(`Failed to load ${theme} theme`, error);
      };
      document.head.appendChild(script);
    },
    /**echarts初始化 */
    initCharts () {
      return new Promise((resolve, reject) => {
        try {
          this.myChart1 = echarts.init(document.getElementById('main1'));
          this.myChart1.setOption(this.option1);

          this.myChart2 = echarts.init(document.getElementById('main2'));
          this.myChart2.setOption(this.option2);

          this.myChart1.on('click', this.handleClick);
          this.myChart2.on('click', this.handleClick);

          this.myChart1.on('dataZoom', this.handleDataZoom);

          resolve();
        } catch (error) {
          reject(error);
        }
      });
    },
    /**更新主题 */
    updateChartsTheme (theme) {
      if (this.myChart1) {
        this.myChart1.dispose();
        this.myChart1 = echarts.init(document.getElementById('main1'), theme);
        this.myChart1.setOption(this.option1);
        this.myChart1.resize();
      }

      if (this.myChart2) {
        this.myChart2.dispose();
        this.myChart2 = echarts.init(document.getElementById('main2'), theme);
        this.myChart2.setOption(this.option2);
        this.myChart2.resize();
      }
    },
    /*  鼠标点击事件*/
    handleClick (params) {
      alert("将为你打开一个新窗口,搜索关键词" + params.name);
      window.open('https://www.baidu.com/s?wd=' + encodeURIComponent(params.name));
    },
    /** 数据放缩*/
    handleDataZoom (params) {
      console.log(params);
      const startValue = this.myChart1.getModel().option.dataZoom[0].startValue;
      const endValue = this.myChart1.getModel().option.dataZoom[0].endValue;
      console.log(startValue, endValue);
      this.option1.dataZoom[0].start = params.start;
      this.option1.dataZoom[0].end = params.end;
      this.myChart1.setOption(this.option1);
    },
    /** 窗口大小改变 */
    handleResize () {
      if (this.myChart1) this.myChart1.resize();
      if (this.myChart2) this.myChart2.resize();
    }
  }
};
</script>